// Copyright (c) Appeon
// The following has been modified by Appeon under compliance with the Apache 2.0 license from the original work

// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Data;
using JetBrains.Annotations;

namespace SnapObjects.Data.Sqlite
{
    public class SqliteDateTimeOffsetTypeMapping : DateTimeOffsetTypeMapping
    {
        private const string DateTimeOffsetFormatConst = @"{0:yyyy\-MM\-dd HH\:mm\:ss.FFFFFFFzzz}";

        /// <summary>
        ///     Initializes a new instance of the <see cref="SqliteDateTimeOffsetTypeMapping" /> class.
        /// </summary>
        /// <param name="dbTypeName"> The name of the database type. </param>
        /// <param name="dbType"> The <see cref="System.Data.DbType" /> to be used. </param>
        public SqliteDateTimeOffsetTypeMapping(
            [NotNull] string dbTypeName,
            [NotNull] DbType? dbType = System.Data.DbType.DateTimeOffset)
            : base(dbTypeName, dbType: dbType)
        {
        }

        /// <summary>
        ///     Creates a copy of this mapping.
        /// </summary>
        /// <param name="dbTypeName"> The name of the database type. </param>
        /// <param name="size"> The size of data the property is configured to store, or null if no size is configured. </param>
        /// <returns> The newly created mapping. </returns>
        public override TypeMapping Clone(string dbTypeName, int? size)
        {
            return new SqliteDateTimeOffsetTypeMapping(dbTypeName, this.DbType);
        }

        /// <summary>
        ///     Gets the string format to be used to generate SQL literals of this type.
        /// </summary>
        protected override string SqlLiteralFormatString => "'" + DateTimeOffsetFormatConst + "'";

        protected override bool IsAssignable(Type modelType, Type dbType)
        {
            // Workaround Microsoft.Data.Sqlite.SqliteDataReader.GetFieldType() issue
            // when the column's value is null in the first record, 
            // the column's dbtype is always int32.
            // so ignore the type mathcing.
            return true;
        }

        public override bool IsStrictAssignable(Type modelType)
        {
            return true;
        }
    }
}
